<template>
  <div ref="wrapper"
       class="wrapper">
    <slot></slot>
  </div>
</template>
<script>
import BScroll from 'better-scroll'
export default {
  name: 'scroll',
  // 父子组件
  props: {
    probeType: {
      type: Number,
      default: 1
    },
    click: {
      type: Boolean,
      default: true
    },
    listenScroll: {
      type: Boolean,
      default: false
    },
    data: {
      type: Array,
      default: null
    },
    pullup: {
      type: Boolean,
      default: false
    },
    beforeScroll: {
      type: Boolean,
      default: false
    },
    refreshDelay: {
      type: Number,
      default: 20
    },
    mouseWheel: {
      type: Object,
      default () {
        return {
          speed: 20,
          invert: false,
          easeTime: 300
        }
      }
    },
    scrollbar: {
      type: Object,
      default () {
        return {
          fade: true,
          interactive: true // 1.8.0 新增
        }
      }
    },
    scrollToBottom: {
      type: Boolean,
      default: false
    }
  },
  mounted () {
    setTimeout(() => {
      this._initScroll()
    }, 20)
  },
  methods: {
    // 初始化
    _initScroll () {
      if (!this.$refs.wrapper) {
        return
      }
      this.scroll = new BScroll(this.$refs.wrapper, {
        probeType: this.probeType,
        click: this.click,
        scrollbar: this.scrollbar,
        mouseWheel: this.mouseWheel
      })
      if (this.listenScroll) {
        let me = this
        this.scroll.on('scroll', pos => {
          me.$emit('scroll', pos)
        })
      }

      if (this.pullup) {
        this.scroll.on('scrollEnd', () => {
          if (this.scroll.y <= this.scroll.maxScrollY + 50) {
            this.$emit('scrollToEnd')
          }
        })
      }

      if (this.beforeScroll) {
        this.scroll.on('beforeScrollStart', () => {
          this.$emit('beforeScroll')
        })
      }
      if (this.scrollToBottom) {
        this.scroll.scrollTo(0, this.scroll.maxScrollY)
      }
    },
    enable () {
      this.scroll && this.scroll.enable()
    },
    refresh () {
      this.scroll && this.scroll.refresh()
    }
  },
  watch: {
    data () {
      // 监听data数组是否有新数据传入
      setTimeout(() => {
        this.refresh()
      }, 20)
    }
  }
}
</script>
<style lang="scss" scoped>
.wrapper {
  height: 100%;
}
</style>
